package cn.xspace.module.other.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.been.Equipment;
import com.xspace.android.xafcommon.util.Constants;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import com.xspace.android.xafcommon.util.RequestConstant;
import com.xspace.android.xafcommon.view.dialog.DialogHelp;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
//import cn.xspace.library.util.L;
import cn.xspace.module.other.R;
import cn.xspace.module.other.util.RProxy;
import cn.xspace.module.other.view.adapter.RecentLoginAdapter;
import com.xspace.android.xafcommon.util.T;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by liuchen on 2016/12/13.
 */

public class RecentLoginActivity extends BaseActivity {

    private ListView mListView;
    private TitleBar mTitlebar;
    private String userId = "";
    private RecentLoginAdapter mAdapter;
    private List<Equipment> mDataList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_recent_login);
    }

    @Override
    protected void initFindViewById() {
        super.initFindViewById();
        mListView = (ListView) findViewById(RProxy.listview);
        mTitlebar = (TitleBar) findViewById(R.id.title_bar);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mTitlebar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                final Equipment eq = mDataList.get(position);
                DialogHelp.getMessageDialog(mContext,
                        String.format(mContext.getResources().getString(R.string.unBind_confirm), eq.manufacturer),
                        mContext.getResources().getString(R.string.unBind_title),
                        mContext.getResources().getString(R.string.cancel),
                        mContext.getResources().getString(R.string.button_ok),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                showWaitDialog();
                                Map<String, Object> dataMap = new HashMap<String, Object>();
                                dataMap.put(RequestConstant.KEY_USER_ID, userId);
                                dataMap.put(RequestConstant.KEY_IMEI, eq.imei);
                                dataMap.put("isdel", 1);
                                registerSubscription(
                                        OkHttpManager.getInstance().commonRequestWithoutEncrypt(Constants.updateUserBondedDevices, dataMap)
                                                .subscribeOn(Schedulers.io())
                                                .observeOn(AndroidSchedulers.mainThread())
                                                .subscribe(new Subscriber<BaseReturnBean>() {
                                                    @Override
                                                    public void onCompleted() {

                                                    }

                                                    @Override
                                                    public void onError(Throwable e) {
                                                        hideWaitDialog();
                                                        T.showSingleL(e.getMessage());

                                                    }

                                                    @Override
                                                    public void onNext(BaseReturnBean baseReturnBean) {
                                                        hideWaitDialog();
                                                        T.showSingleL("解除成功");
                                                        mDataList.remove(position);
                                                        mAdapter.notifyDataSetChanged();
                                                    }
                                                })
                                );


                            }
                        }, null)
                        .show();
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        userId = MyInfoUtil.getMyUserid(mContext);
        mAdapter = new RecentLoginAdapter(mContext, mDataList);
        mTitlebar.setTitle(mContext.getResources().getString(R.string.record_recent_login));
        mListView.setAdapter(mAdapter);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put(RequestConstant.KEY_USER_ID, userId);
        showWaitDialog();
        registerSubscription(
                OkHttpManager.getInstance().commonRequestWithoutEncrypt(Constants.queryUserBondedDevices, dataMap)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .map(new Func1<BaseReturnBean, List<Equipment>>() {
                            @Override
                            public List<Equipment> call(BaseReturnBean baseReturnBean) {
//                                L.v("call");

                                List<Equipment> deviceList = new ArrayList<Equipment>();
                                try {
                                    JSONArray jsonArray = new JSONArray(baseReturnBean.data);
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        Equipment equipment = new Equipment();
                                        JSONObject jsonObj = jsonArray.getJSONObject(i);
                                        equipment.imei = jsonObj.optString("imei");
                                        equipment.osversion = jsonObj.optString("osversion");
                                        equipment.manufacturer = jsonObj.optString("manufacturer");
                                        equipment.isBind = "0".equals(jsonObj.optString("isdel"));
                                        if (equipment.isBind) {
                                            deviceList.add(equipment);
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                return deviceList;
                            }
                        })
                        .subscribe(new Subscriber<List<Equipment>>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                hideWaitDialog();
                                T.showSingleL(e.getMessage());
                            }

                            @Override
                            public void onNext(List<Equipment> dataList) {
//                                L.v("onNext" + dataList.size());
                                hideWaitDialog();
                                mDataList.addAll(dataList);
                                mAdapter.notifyDataSetChanged();
                            }
                        })
        );
    }
}
